package org.example.service;

import org.example.model.AvatarSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class AvatarSessionManager {
    private static final Logger logger = LoggerFactory.getLogger(AvatarSessionManager.class);

    // 存储所有活跃的数字人会话
    private final Map<String, AvatarSession> activeSessions = new ConcurrentHashMap<>();

    @Autowired
    private AvatarService avatarService;

    @Value("${aliyun.avatar.session-timeout:3600000}") // 默认1小时
    private long sessionTimeout;

    /**
     * 创建新的数字人会话
     */
    public AvatarSession createSession() throws Exception {
        AvatarSession session = avatarService.startInstance();
        activeSessions.put(session.getSessionId(), session);
        return session;
    }

    /**
     * 获取已存在的会话
     */
    public AvatarSession getSession(String sessionId) {
        AvatarSession session = activeSessions.get(sessionId);
        if (session != null) {
            // 更新心跳时间
            session.updateHeartbeat();
        }
        return session;
    }

    /**
     * 关闭会话
     */
    public void closeSession(String sessionId) {
        AvatarSession session = activeSessions.get(sessionId);
        if (session != null) {
            try {
                avatarService.stopInstance(sessionId);
                session.setStatus("closed");
            } catch (Exception e) {
                logger.error("关闭数字人会话异常: {}", sessionId, e);
            } finally {
                activeSessions.remove(sessionId);
            }
        }
    }

    /**
     * 发送文本到数字人
     */
    public void sendText(String sessionId, String text) throws Exception {
        AvatarSession session = getSession(sessionId);
        if (session == null) {
            throw new Exception("数字人会话不存在或已过期");
        }

        // 默认不打断当前播报
        avatarService.sendText(sessionId, text, false);
        session.updateHeartbeat();
    }

    /**
     * 发送文本到数字人（可选择是否打断当前播报）
     */
    public void sendText(String sessionId, String text, boolean interrupt) throws Exception {
        AvatarSession session = getSession(sessionId);
        if (session == null) {
            throw new Exception("数字人会话不存在或已过期");
        }

        avatarService.sendText(sessionId, text, interrupt);
        session.updateHeartbeat();
    }

    /**
     * 打断当前数字人播报
     */
    public void interruptSpeaking(String sessionId) throws Exception {
        AvatarSession session = getSession(sessionId);
        if (session == null) {
            throw new Exception("数字人会话不存在或已过期");
        }

        avatarService.sendCommand(sessionId, "INTERRUPT", null);
        session.updateHeartbeat();
    }

    /**
     * 定时检查过期会话并清理
     * 每5分钟执行一次
     */
    @Scheduled(fixedRate = 300000)
    public void cleanupExpiredSessions() {
        long now = System.currentTimeMillis();
        logger.debug("开始清理过期的数字人会话...");

        activeSessions.forEach((sessionId, session) -> {
            // 检查会话是否超时
            if (now - session.getLastHeartbeat() > sessionTimeout) {
                logger.info("数字人会话超时，准备关闭: {}", sessionId);
                closeSession(sessionId);
            }
        });
    }

    /**
     * 获取当前活跃会话数
     */
    public int getActiveSessionCount() {
        return activeSessions.size();
    }
}
